package com.blaze.framework.core.boot.argumentresolver;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blaze.framework.starter.mybatis.plus.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 分页参数解析器
 * @author created by Zhou Zongbo on 2025/5/30.
 */
@Slf4j
public class PageArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(Page.class);
    }

    @Override
    public Object resolveArgument(@NonNull MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  @NonNull NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
        int pageNum = getIntParam(webRequest, PageUtil.PAGE_NUM, PageUtil.DEFAULT_PAGE_NUM);
        int pageSize = getIntParam(webRequest, PageUtil.PAGE_SIZE, PageUtil.DEFAULT_PAGE_SIZE);
        String orderBy = webRequest.getParameter(PageUtil.ORDER_BY);
        Page<Object> page = new Page<>(pageNum, pageSize);
        PageUtil.getOrderItem(orderBy).ifPresent(page::addOrder);
        return page;
    }

    public int getIntParam(@NonNull NativeWebRequest webRequest, String paramName, int defaultValue) {
        String parameter = webRequest.getParameter(paramName);
        if (StringUtils.isNotBlank(parameter)) {
            try {
                return Integer.parseInt(parameter);
            } catch (Exception ex) {
                log.warn("参数 {} 解析失败，使用默认值: {}", parameter, defaultValue);
            }
        }
        return defaultValue;
    }
}
